package com.gistmap.ntdc.web;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.gistmap.ntdc.config.WxMaConfiguration;
import com.gistmap.ntdc.exception.ErrorItems;
import com.gistmap.ntdc.exception.ServiceException;
import com.gistmap.ntdc.model.LoginWrapper;
import com.gistmap.ntdc.response.Result;
import com.gistmap.ntdc.service.UserService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

/**
 * @author zhangran
 * @date 2018/12/12
 */
@Slf4j
@RestController
@RequestMapping("/wx/user/{appid}")
public class WxUserController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserService userService;

    @GetMapping("/login")
    public Result login(@PathVariable String appid, String code){
        if (StringUtils.isBlank(code)) {
            throw new ServiceException(ErrorItems.CODE_IS_NULL);
        }
        final WxMaService wxMaService = WxMaConfiguration.getMaService(appid);
        try {
            WxMaJscode2SessionResult sessionResult = wxMaService.getUserService().getSessionInfo(code);
            log.info(sessionResult.getOpenid());
            log.info(sessionResult.getSessionKey());
            return new Result().success(sessionResult);
        } catch (WxErrorException e) {
            log.error(e.getMessage(), e);
            return new Result().error(e.toString(), 0);
        }
    }

    @PostMapping("/update")
    public Result update(@PathVariable String appid, @RequestBody LoginWrapper loginWrapper){
        log.info(loginWrapper.toString());

        final WxMaService wxService = WxMaConfiguration.getMaService(appid);
        // 用户信息校验
        if (!wxService.getUserService().checkUserInfo(loginWrapper.sessionKey, loginWrapper.rawData,
                loginWrapper.signature)) {
            throw new ServiceException(ErrorItems.USER_NOT_CHECK);
        }

        // 解密用户信息
        WxMaUserInfo userInfo = wxService.getUserService().getUserInfo(loginWrapper.sessionKey,
                loginWrapper.encryptedData, loginWrapper.iv);

        log.info(userInfo.toString());

        // token
        String token = UUID.randomUUID().toString();

        // 保存用户信息
        userService.save(userInfo, token);

        return new Result().success(token);
    }

}
